﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace NET6.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CacheController : ControllerBase
    {
        private readonly IMemoryCache _cache;

        public CacheController(IMemoryCache cache)
        {
            _cache = cache;
        }

        [HttpPost]
        public IActionResult Set(string key = "key", string data = "数据", int second = 30)
        {
            var cacheOptions = new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(TimeSpan.FromSeconds(second));

            _cache.Set(key, data, cacheOptions);

            return Ok();
        }

        [HttpGet]
        public IActionResult Get(string key = "key")
        {
            if (_cache.TryGetValue(key, out string data))
            {
                return Ok(data);
            }

            return NoContent();
        }

        [HttpPost]
        public IActionResult Del(string key = "key")
        {
            _cache.Remove(key);

            return Ok();
        }
    }
}
